#include "I_BaseLib.h"

void BASE_RENDERER::DrawLine(COLOR col,int from_x, int from_y, int to_x, int to_y,int thickness)
{
	//Bresenham variation
	int delta_x,delta_y;
	delta_x=abs(from_x-to_x);
	delta_y=abs(from_y-to_y);

	int sign_x,sign_y;
	if (delta_x>0) sign_x = (to_x-from_x) / delta_x;
	else sign_x = 0;
	if (delta_y>0) sign_y = (to_y-from_y) / delta_y;
	else sign_y = 0;

	float real_inc;
	bool xisbigger;

	if ( ( real_inc = (float)delta_x / (float)delta_y ) < 1.0f ) xisbigger=false;
	else {real_inc = (float)delta_y / (float)delta_x; xisbigger=true;}

	//if x distance is bigger, we have to make bigger steps
	//the x steps are whole steps, while the y steps == real_inc
	if (xisbigger)
	{
		for (float x=(float)from_x, y=(float)from_y;x!=(float)to_x && y!=(float)to_y;x+=(float)sign_x,y+=real_inc*sign_y)
		{
			//Antialias line 1
			framebuffer->PutPixel(col.AlphaBlend(framebuffer->GetPixel((int)x,(int)y-thickness),1-GetFraction(y)),(int)x,(int)y-thickness);

			//center lines
			for (int t=-(thickness-1);t<=(thickness-1);t++)
				framebuffer->PutPixel(col,(int)x,(int)y+t);

			//Antialias line 2
			framebuffer->PutPixel(col.AlphaBlend(framebuffer->GetPixel((int)x,(int)y+thickness),GetFraction(y)),(int)x,(int)y+thickness);
		}
	}
	else
		for (float x=(float)from_x, y=(float)from_y;x!=(float)to_x && y!=(float)to_y;x+=real_inc*sign_x,y+=(float)sign_y)
		{
			//Antialias line 1
			framebuffer->PutPixel(col.AlphaBlend(framebuffer->GetPixel((int)x-thickness,(int)y),1-GetFraction(x)),(int)x-thickness,(int)y);

			//center lines
			for (int t=-(thickness-1);t<=(thickness-1);t++)
				framebuffer->PutPixel(col,(int)x+t,(int)y);

			//Antialias line 2
			framebuffer->PutPixel(col.AlphaBlend(framebuffer->GetPixel((int)x+thickness,(int)y),GetFraction(x)),(int)x+thickness,(int)y);
		}

		if (from_x == to_x)
			for (int y=from_y;y!=to_y;y+=sign_y)
			{
				//center lines
				for (int t=-(thickness);t<=(thickness-1);t++)
					framebuffer->PutPixel(col,(int)from_x+t,(int)y);
			}

			if (from_y == to_y)
				for (int x=from_x;x!=to_x;x+=sign_x)
				{
					//center lines
					for (int t=-(thickness);t<=(thickness-1);t++)
						framebuffer->PutPixel(col,(int)x,(int)from_y+t);
				}
}

void BASE_RENDERER::DrawRectangle(int from_x, int from_y, int to_x, int to_y, COLOR col, int thickness)
{
	DrawLine(col,from_x,from_y,to_x,from_y,thickness);
	DrawLine(col,to_x,from_y,to_x,to_y,thickness);
	DrawLine(col,to_x,to_y,from_x,to_y,thickness);
	DrawLine(col,from_x,to_y,from_x,from_y,thickness);
}

